package com.atguigu.crowd.service.impl;

import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.entity.AdminExample;
import com.atguigu.crowd.entity.AdminExample.Criteria;
import com.atguigu.crowd.exception.LoginAccAlreadInUserException;
import com.atguigu.crowd.exception.LoginFailedException;
import com.atguigu.crowd.mapper.AdminMapper;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.util.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class AdminServiceImpl implements AdminService {

	@Autowired
	private AdminMapper adminMapper;
	
	//为了更详细的显示出错误日志，我们加上这行代码
	private Logger logger=LoggerFactory.getLogger(AdminServiceImpl.class);
	
	@Override
	public void saveAdmin(Admin admin) {
		
		adminMapper.insert(admin);
		//throw new RuntimeException();//触发回滚
	}
	@Override
	public List<Admin> getAll() {
		// TODO Auto-generated method stub
		return adminMapper.selectByExample(new AdminExample());
	}
	@Override
	public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
		
		//1、根据登录的账号查询Admin对象
		//a、创建AdminExample对象
		AdminExample adminExample=new AdminExample();
		//b、创建Criteria对象中封装查询条件
		Criteria criteria = adminExample.createCriteria();
		//c、在Criteria 对象中封装查询条件
		criteria.andLoginAcctEqualTo(loginAcct);
		//d、调用AdminMapper的方法执行查询
		List<Admin> list=adminMapper.selectByExample(adminExample);
		
		//2、判断Admin对象是否为null
		if(list==null||list.size()==0) {
			throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
		}
		if(list.size()>1) {
			//admin记录有多个说明账号重复了
			throw new LoginFailedException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
		}
		
		Admin admin=list.get(0);//这样去获取到唯一的 admin 对象
		
		//3、如果Admin 对象为null 则抛出 异常
		if(admin==null) {
			throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
		}
		
		//4、如果Admin对象不为null 则将数据库密码从Admin对象中取出
		String userPswdDB=admin.getUserPswd();
		
		//5、将表单提交的明文密码进行加密
		String userPswdForm=CrowdUtil.md5(userPswd);
		
		//6、对密码进行比较
		if(!Objects.equals(userPswdDB,userPswdForm)) {
			//7、如果比较结果不一致则抛出异常
			throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
		}
		
		//8、如果一致则返回Admin对象
		return admin;
	}
	@Override
	public List<Admin> selectAdminByKeyword() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
		
		//1、调用PageHelper的静态方法开启分页功能
		//这里充分体现了PageHelper的"非侵入式"设计，原本要做的查询不必有任何的修改（看第2步，分页和不分页都是一样的代码，完全没有任何影响）
		PageHelper.startPage(pageNum, pageSize);
		
		//2、执行查询
		List<Admin> list=adminMapper.selectAdminByKeyword(keyword);
		
		//3、封装到PageInfo对象中
		
		return new PageInfo<>(list);
	}
	@Override
	public void adminDeleteOne(Integer id) {
		adminMapper.deleteByPrimaryKey(id);
	}
	@Override
	public int adminAddOne(Admin admin) {
		
		try {
			return adminMapper.insert(admin);
		} catch (Exception e) {
			
			e.printStackTrace();
			logger.info("异常全类名="+e.getClass());
			
			if(e instanceof DuplicateKeyException ) {
				//如果在这里是这个类（DuplicateKeyException）异常， 那么我们抛出我们的自定义类 （LoginAccAlreadInUserException)，表名是新增的时候，账号异常了
				throw new LoginAccAlreadInUserException(CrowdConstant.MESSAGE_LOGIN_ACCT_IN_UES);
			}
			
			return -1;
		}
	

	}
	@Override
	public Admin getAdminByPrimaryKey(Integer id) {

		return adminMapper.selectByPrimaryKey(id);
	}
	@Override
	public void updateByExampleSelective(Admin admin) {
		// TODO Auto-generated method stub
		adminMapper.updateByPrimaryKeySelective(admin);
	}
	@Override
	public int adminDeleteArray(List<Integer> ids) {
		int result=0;
		for (Integer id : ids) {
			
			result = adminMapper.deleteByPrimaryKey(id);

		}
		return result;
	}

	/**
	 * 保存用户和角色关系
	 * @param adminId
	 * @param roleIdList
	 */
	@Override
	public void saveAdminRoleRalationship(Integer adminId, List<Integer> roleIdList) {

		//分两步
		//1、根据adminId 删除旧的关联关系

		int result = adminMapper.deleteOldRelationship(adminId);
		int restltNew = 0;
		//2、根据roleIdList 和adminId保存新的 关联关系

		if (roleIdList!=null && roleIdList.size() > 0){
			 restltNew = adminMapper.insertNewRelationship(adminId,roleIdList);
		}

	}

}
























